package repository.relsys.services.spring;

import repository.relsys.domainmodel.general.*;

import repository.relsys.util.urigeneretor.*;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RelsysResourceFactory {

	
	private static ApplicationContext context;
	private String namespace;
	
	
	public RelsysResourceFactory() {
		context = createContext();
		namespace = "http://diplomski.nelakolundzija.org/store#";
	}
	public RelsysResourceFactory(String ns){
		if(!ns.endsWith("/") && !ns.endsWith("#")){
			ns = ns + "#";
		}
		context = createContext();
		namespace = ns;
	}

	private ApplicationContext createContext() {
		AbstractApplicationContext context = new ClassPathXmlApplicationContext(
				getContextLocations());
    	context.registerShutdownHook();
    	return context;
	}


	private String[] getContextLocations() {
		String[] mappings = new String[]{
				"META-INF/domainmodel/general.xml", 
				"META-INF/domainmodel/learningTool.xml", 
				};
		return mappings;
	}
	
	public ApplicationContext getContext() {
		if (context == null) context = createContext();
		return context;
	}
	
	@SuppressWarnings("unchecked")
	public Object createResource(Class clazz ){
		Resource r = (Resource) context.getBean(clazz.getName());
		r.setUri(URIBuilder.instance().generateURI(r, namespace));
		return r;
	}

	@SuppressWarnings("unchecked")
	public Class getBeanImplementationClass(Class clazz) {
		return context.getBean(clazz.getName()).getClass();
	}
	
	
}
